/**
 * 演示程序当前的 “注册/登录” 等操作，是基于 “本地存储” 完成的
 * 当您要参考这个演示程序进行相关 app 的开发时，
 * 请注意将相关方法调整成 “基于服务端Service” 的实现。
 **/

(function($, owner) {
	
	//========================用户登录=========================================
	owner.login = function(loginInfo, callback) {
		
		callback = callback || $.noop;
		loginInfo = loginInfo || {};
		loginInfo.account = loginInfo.account || '';
		loginInfo.password = loginInfo.password || '';
		if(loginInfo.account==''||loginInfo.password==''){
			return callback('用户名或密码不能为空');
		}		
		var url = "http://123.56.76.128:8080/hyzapp/appuser/login";
		plus.nativeUI.showWaiting("登录中..");
		$.ajax({
			type:"post",
			url:url,
			async:true,
			timeout:10000,//设置网络超时值
			data:{"USERNAME":loginInfo.account,"PASSWORD":loginInfo.password},
			datatype:'json',
			success: function(data){
				console.log("login--success");
				plus.nativeUI.closeWaiting();
				var json = JSON.stringify(data);
				var obj = eval('(' + json + ')');		
				//登录成功跳转首页面----zzf
				if(obj.result=='登录成功'){
					if(obj.pd.NAME=='demo'){
						obj.pd.NAME = '未设置昵称';
					}
//					alert(json);
					var users = JSON.parse(localStorage.getItem('$users') || '[]');
					var authed = users.some(function(user) {
					return loginInfo.account == user.account && loginInfo.password == user.password;
					});
					if (authed) {
					return owner.createState(loginInfo.account, obj.pd.vdef2,obj.pd.NAME,callback);
					} else {
					return owner.createState(loginInfo.account,obj.pd.vdef2,obj.pd.NAME,callback);
						}
					return callback('登录成功');
					}				 
					
				//用户名或密码错误----zzf
				if(obj.result=='用户名或邮箱或密码错误'){
					return callback('用户名或密码错误');
				}
			},
			error:function(xhr, type, errorThrown) {              
				//console.log(JSON.stringify(xhr));
				plus.nativeUI.closeWaiting();
				$.toast("登陆失败，请检查网络设置");
			}
		});	
		console.log("2");
	};
	owner.createState = function(name,vdef2,nickname,callback) {
		var state = owner.getState();
		state.account = name;
		state.token = "token123456789";
		state.nickname = nickname;
		state.phone = "未绑定";
		//增加字段与商城相连的用户ID
		state.customerID=vdef2;
		owner.setState(state);
		return callback();
	};

	/**
	 * 新用户注册==============================================================
	 **/
	owner.reg = function(regInfo, callback) {
		callback = callback || $.noop;
		regInfo = regInfo || {};
		regInfo.account = regInfo.account;
		regInfo.password = regInfo.password;
		regInfo.email = regInfo.email;
		//var msgflag = '1';//0表示失败,1表示成功
		//用户名校验
		if(regInfo.account==''){
			return callback('用户名不能为空');
		}
		//密码校验
		if(regInfo.password==''){
			return callback('密码不能为空');
		}
		//邮箱校验
		if (!checkEmail(regInfo.email)) {
			return callback('邮箱地址不合法');
		}
	
		var url = "http://123.56.76.128:8080/hyzapp/appuser/getAppuserByUsername";	
		var username = regInfo.account;
		$.ajax({
			type:"post",
			url:url,
			async:true,
			data:{"USERNAME":username},
			datatype:'json',
			success: function(data){				
				var jsons = JSON.stringify(data);
				var obj = eval('(' + jsons + ')');				
				if(obj.result=='请求成功'){
					return callback('用户名已存在，请输入其他用户名');
					}else{						
						url = "http://123.56.76.128:8080/hyzapp/appuser/getAppuserByEmail";
						$.ajax({
						type:"post",
						url:url,
						async:true,
						data:{"EMAIL":regInfo.email},
						datatype:'json',
						success: function(data){				
						var jsonsa = JSON.stringify(data);
						var obj = eval('(' + jsonsa + ')');
						if(obj.result=='请求成功'){
							return callback('此邮箱已被注册');
						}else{
							url = "http://123.56.76.128:8080/hyzapp/appuser/addAppuser";		
						$.ajax({
						type:"post",
						url:url,
						async:true,
						data:{"USERNAME":regInfo.account,"PASSWORD":regInfo.password,"EMAIL":regInfo.email,"NAME":"demo"},
						datatype:'json',
						success: function(data){				
						var json = JSON.stringify(data);
						var obj = eval('(' + json + ')');	

						//注册成功跳转登录页面----	zzf
						if(obj.result=='添加成功'){	
							
							var users = JSON.parse(localStorage.getItem('$users') || '[]');
							users.push(regInfo);
							localStorage.setItem('$users', JSON.stringify(users));
							return callback();
							return callback('注册成功');
						}				 
						}
						});
						}
						}
						});
					}
			}
		});			
	};
	
	
	
	/**
	 * 获取当前状态
	 **/
	owner.getState = function() {
		var stateText = localStorage.getItem('$state') || "{}";
		return JSON.parse(stateText);
	};

	/**
	 * 设置当前状态
	 **/
	owner.setState = function(state) {
		state = state || {};
		localStorage.setItem('$state', JSON.stringify(state));
		//var settings = owner.getSettings();
		//settings.gestures = '';
		//owner.setSettings(settings);
	};

	var checkEmail = function(email) {
		email = email || '';
		return (email.length > 3 && email.indexOf('@') > -1);
	};

	/**
	 * 找回密码
	 **/
	owner.forgetPassword = function(email, callback) {
		callback = callback || $.noop;
		if (!checkEmail(email)) {
			return callback('邮箱地址不合法');
		}
		return callback(null, '新的随机密码已经发送到您的邮箱，请查收邮件。');
	};
	
	/**
	 * 车辆缴费立即支付点击事件触发更新后台失效日期
	 */
	function updateEnddate(carno,enddate){
		var url = "http://123.56.76.128:8080/hyzapp/appCarfare/updateEnddate";
		ajax({
				type: "get",
				url: url,
				contentType:"application/x-www-form-urlencoded; charset=utf-8", 
				data: {
					"enddate": enddate,
					"number":carno
					},
				datatype: 'json',
				success: function(data) {}
			});
	}


	/**
	 * 获取应用本地配置
	 **/
	owner.setSettings = function(settings) {
		settings = settings || {};
		localStorage.setItem('$settings', JSON.stringify(settings));
	}

	/**
	 * 设置应用本地配置
	 **/
	owner.getSettings = function() {
			var settingsText = localStorage.getItem('$settings') || "{}";
			return JSON.parse(settingsText);
		}
		/**
		 * 获取本地是否安装客户端
		 **/
	owner.isInstalled = function(id) {
		if (id === 'qihoo' && mui.os.plus) {
			return true;
		}
		if (mui.os.android) {
			var main = plus.android.runtimeMainActivity();
			var packageManager = main.getPackageManager();
			var PackageManager = plus.android.importClass(packageManager)
			var packageName = {
				"qq": "com.tencent.mobileqq",
				"weixin": "com.tencent.mm",
				"sinaweibo": "com.sina.weibo"
			}
			try {
				return packageManager.getPackageInfo(packageName[id], PackageManager.GET_ACTIVITIES);
			} catch (e) {}
		} else {
			switch (id) {
				case "qq":
					var TencentOAuth = plus.ios.import("TencentOAuth");
					return TencentOAuth.iphoneQQInstalled();
				case "weixin":
					var WXApi = plus.ios.import("WXApi");
					return WXApi.isWXAppInstalled()
				case "sinaweibo":
					var SinaAPI = plus.ios.import("WeiboSDK");
					return SinaAPI.isWeiboAppInstalled()
				default:
					break;
			}
		}
	}
}(mui, window.app = {}));